import { Modal, Form, message } from 'antd';
import ProForm, { ProFormText, ProFormTextArea, ProFormDigit } from '@ant-design/pro-form';
import { save, update, checkValue } from '@/services/system/dict';

const SystemDictForm = (props) => {

  const [form] = Form.useForm();
  const { formVisible, onSubmit, onCancel, values } = props;

  const saveHandle = async (formValue) => {
    const data = await save(formValue);

    if (data.success) message.success('新建字典成功!');
    else message.error('新建字典失败!');
  };

  const updateHandle = async (formValue) => {
    const data = await update(formValue);

    if (data.success) message.success('修改字典成功!');
    else message.error('修改字典失败!');
  };

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    const formValue = { ...values, ...fieldsValue };

    if (formValue.id) await updateHandle(formValue);
    else await saveHandle(formValue);

    onSubmit();
  }

  const validatorValue = (rule, value, callback) => {
    if (value) {
      checkValue({ id: values.id, value: value, parentId: values.parentId}).then((result) => {
        if (result.success) {
          callback("字典键值已被使用");
        } else {
          callback();
        }
      });
    } else {
      callback();
    }
  };

  return (
    <Modal
      destroyOnClose
      title={values.id ? '修改字典信息' : '新增字典信息'}
      visible={formVisible}
      onOk={okHandle}
      onCancel={onCancel}
    >
      <ProForm 
        initialValues={{
          label: values.label,
          value: values.value,
          sort: values.sort,
          remark: values.remark,
          parentLabel: values.parentLabel
        }} 
        form={form} submitter={false}
        layout={'horizontal'} labelCol= { {span: 4} } wrapperCol= { {span: 20} }
      >
        {
          values.parentLabel ? (
            <ProFormText  name="parentLabel" label="上级字典" readonly />
          ) : null
        }
        <ProFormText  name="label" label="字典标签" rules={[{ required: true, message: '请输入字典标签!' }, {max: 50, message: '字典标签过长!'}]}/>
        <ProFormText  name="value" label="字典键值" 
          rules={[{ required: true, message: '请输入字典键值!' }, {max: 50, message: '字典键值过长!'}, {validator: validatorValue}]}
        />
        <ProFormDigit name="sort" label="字典排序" min={1} max={10000} defaultValue={1} rules={[{ required: true, message: '请输入字典排序!' }]}/>
        <ProFormTextArea  label="备注说明" name="remark" rules={[ {max: 100, message: '备注过长!'}]}/>
      </ProForm>
    </Modal>
  );
}

export default SystemDictForm;